package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"shop_srvs/order_srv/global"
	"shop_srvs/order_srv/model"
	"shop_srvs/order_srv/proto"
)

func (Order) CartItemList(ctx context.Context, req *proto.UserInfo) (*proto.CartItemListResponse, error) {
	//获取用户的购物车列表
	var shopCarts []model.ShoppingCart
	if result := global.DB.Where(&model.ShoppingCart{User: req.Id}).Find(&shopCarts); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "没有购物车信息")
	}

	var data []*proto.CartItemResponse
	for _, shopCart := range shopCarts {
		data = append(data, &proto.CartItemResponse{
			Id:      shopCart.ID,
			UserId:  shopCart.User,
			GoodsId: shopCart.Goods,
			Nums:    shopCart.Nums,
			Checked: shopCart.Checked,
		})
	}
	return &proto.CartItemListResponse{
		Total: int32(len(shopCarts)),
		Data:  data,
	}, nil
}
func (Order) CreateCartItem(ctx context.Context, req *proto.CartItemRequest) (*proto.CartItemResponse, error) {
	//获取用户的购物车某个商品记录
	var shopCart model.ShoppingCart
	if result := global.DB.Where(&model.ShoppingCart{User: req.Id, Goods: req.GoodsId}).
		First(&shopCart); result.RowsAffected == 1 {
		//如果记录已经存在，则合并购物车记录, 更新操作
		shopCart.Nums += req.Num
	} else {
		shopCart.User = req.UserId
		shopCart.Goods = req.GoodsId
		shopCart.Nums = req.Num
		shopCart.Checked = false
	}

	global.DB.Save(&shopCart)
	return &proto.CartItemResponse{
		Id:      shopCart.ID,
		Checked: shopCart.Checked,
	}, nil
}
func (Order) UpdateCartItem(ctx context.Context, req *proto.CartItemRequest) (*emptypb.Empty, error) {
	//更新购物车记录，更新数量和选中状态
	var shopCart model.ShoppingCart
	//应该区别用户身份
	if result := global.DB.Where("goods=? and user=?", req.GoodsId, req.UserId).First(&shopCart); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "没有购物车信息")
	}

	shopCart.Checked = req.Checked
	if req.Num > 0 {
		shopCart.Nums = req.Num
	}
	global.DB.Save(&shopCart)
	return &emptypb.Empty{}, nil
}
func (Order) DeleteCartItem(ctx context.Context, req *proto.CartItemRequest) (*emptypb.Empty, error) {
	var shopCart model.ShoppingCart
	//应该区别用户身份
	if result := global.DB.Where("goods=? and user=?", req.GoodsId, req.UserId).Delete(&shopCart); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "没有购物车信息")
	}
	return &emptypb.Empty{}, nil
}
